<template>
  <div class="schedule-result-page">
    <div class="page-header">
      <el-row :gutter="20">
        <el-col :span="18">
          <h1>{{ pageTitle }}</h1>
          <p class="subtitle">{{ algorithmDisplayName }} - 执行时间: {{ executionTime }}ms</p>
        </el-col>
        <el-col :span="6" class="header-actions">
          <el-button @click="goBack">返回</el-button>
          <el-button 
            v-if="scheduleResult?.success" 
            type="primary" 
            @click="savePlan"
            :loading="saving"
          >
            保存为正式计划
          </el-button>
        </el-col>
      </el-row>
    </div>

    <div v-if="scheduleResult" class="page-content">
      <!-- 排产状态提示 -->
      <el-alert 
        :title="scheduleResult.success ? '排产执行成功！' : '排产执行失败！'"
        :type="scheduleResult.success ? 'success' : 'error'"
        :description="scheduleResult.errorMessage"
        show-icon
        style="margin-bottom: 20px;"
      />

      <div v-if="scheduleResult.success">
        <!-- 统计信息 -->
        <el-card class="stats-card" style="margin-bottom: 20px;">
          <template #header>
            <h3>排产统计信息</h3>
          </template>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ scheduleResult.totalWorkOrders }}</div>
                <div class="stat-label">工单数量</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ scheduleResult.totalTasks }}</div>
                <div class="stat-label">生产任务数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ scheduleResult.totalMachines }}</div>
                <div class="stat-label">涉及机器数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ (scheduleResult.totalUtilization ).toFixed(1) }}%</div>
                <div class="stat-label">设备利用率</div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="12">
              <div class="time-info">
                <strong>开始时间：</strong>{{ scheduleResult.scheduleStartTime }}
              </div>
            </el-col>
            <el-col :span="12">
              <div class="time-info">
                <strong>结束时间：</strong>{{ scheduleResult.scheduleEndTime }}
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 甘特图 -->
        <div class="gantt-section" style="margin-bottom: 20px;">
          <schedule-gantt-chart 
            ref="ganttChartRef"
            :plan-data="planData"
            :production-tasks="scheduleResult.productionTasks"
            :schedule-details="scheduleResult.scheduleDetails"
          />
        </div>

        <!-- 详细数据表格 -->
        <el-card class="table-card">
          <template #header>
            <h3>生产任务详细数据</h3>
          </template>
          <el-table 
            :data="scheduleResult.productionTasks" 
            border 
            stripe
            height="400"
            style="width: 100%"
          >
            <el-table-column prop="taskId" label="任务ID" width="150" fixed="left" sortable />
            <el-table-column prop="workOrderId" label="工单ID" width="150" sortable />
            <el-table-column prop="operationId" label="工序ID" width="150" sortable />
            <el-table-column prop="machineId" label="机器ID" width="120" sortable />
            <el-table-column prop="quantity" label="数量" width="80" sortable />
            <el-table-column prop="standardTime" label="标准时间(分)" width="120" sortable />
            <el-table-column prop="plannedTime" label="计划时间(分)" width="120" sortable />
            <el-table-column prop="status" label="状态" width="100" sortable />
            <el-table-column prop="planStartTime" label="计划开始" width="140" sortable />
            <el-table-column prop="planEndTime" label="计划结束" width="140" sortable />
          </el-table>
        </el-card>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-else class="loading-container">
      <el-empty description="正在加载排产结果...">
        <el-button type="primary" @click="goBack">返回</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import ScheduleGanttChart from '@/components/ScheduleGanttChart.vue';
import axios from 'axios';

const route = useRoute();
const router = useRouter();
const ganttChartRef = ref(null);

const scheduleResult = ref(null);
const planData = ref({});
const saving = ref(false);

const API_BASE_URL = 'http://117.72.45.141:8091';

// 算法名称映射
const algorithmNameMap = {
  'PRODUCT_BATCH': '同种产品集中生产算法', 
  'MACHINE_UTILIZATION': '负载均衡算法',
  'ENHANCED_GENETIC_ALGORITHM': '增强遗传算法',
  'DEFAULT_FIFO': 'FIFO默认排序算法',
  'CRITICAL_PATH_SPT': '关键路径SPT算法',
  "COMBINE_ALGORITHM": '紧急优先与机器利用率结合算法'
};

// 计算属性
const pageTitle = computed(() => {
  return planData.value.planName || '排产结果';
});

const algorithmDisplayName = computed(() => {
  const algorithm = planData.value.algorithmType;
  return algorithmNameMap[algorithm] || algorithm || '未知算法';
});

const executionTime = computed(() => {
  return scheduleResult.value?.executionTimeMs || 0;
});

// 从路由参数或状态中获取数据
const loadScheduleResult = () => {
  console.log('加载排产结果数据...');
  console.log('路由查询参数:', route.query);
  
  // 从路由状态中获取数据
  if (route.params.scheduleData) {
    try {
      const data = JSON.parse(decodeURIComponent(route.params.scheduleData));
      scheduleResult.value = data.scheduleResult;
      planData.value = data.planData;
      console.log('从路由参数加载数据成功:', data);
    } catch (error) {
      console.error('解析路由数据失败:', error);
      ElMessage.error('数据加载失败');
    }
  }
  // 从sessionStorage中获取数据
  else if (sessionStorage.getItem('scheduleResult')) {
    try {
      const data = JSON.parse(sessionStorage.getItem('scheduleResult'));
      scheduleResult.value = data.scheduleResult;
      planData.value = data.planData;
      console.log('从sessionStorage加载数据成功:', data);
    } catch (error) {
      console.error('解析sessionStorage数据失败:', error);
      ElMessage.error('数据加载失败');
    }
  }
  else {
    console.warn('未找到排产结果数据');
    ElMessage.warning('未找到排产结果数据，请重新执行排产');
  }
};

// 保存排产计划
const savePlan = async () => {
  saving.value = true;
  try {
    // 从sessionStorage获取保存的订单ID
    let orderIds = [];
    if (sessionStorage.getItem('scheduleResult')) {
      try {
        const data = JSON.parse(sessionStorage.getItem('scheduleResult'));
        orderIds = data.orderIds || [];
      } catch (error) {
        console.warn('获取订单ID失败:', error);
      }
    }
    
    const scheduleForm = {
      planName: planData.value.planName,
      algorithmType: planData.value.algorithmType,
      orderIds: orderIds,
      scheduleStartTime: scheduleResult.value.scheduleStartTime,
      createdBy: localStorage.getItem('username') || '系统用户',
      remark: `通过${algorithmDisplayName.value}算法生成`
    };
    
    console.log('保存排产计划，请求数据:', scheduleForm);
    
    const response = await axios.post(`${API_BASE_URL}/api/schedule/save`, scheduleForm, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    console.log('保存排产计划响应:', response.data);
    
    if (response.data.code === 200) {
      ElMessage.success('排产计划保存成功');
      goBack();
    } else {
      console.error('保存失败:', response.data);
      ElMessage.error(response.data.message || '保存失败');
    }
  } catch (error) {
    console.error('保存排产计划失败:', error);
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message);
    } else {
      ElMessage.error('保存失败，请检查网络连接');
    }
  } finally {
    saving.value = false;
  }
};

// 返回上一页
const goBack = () => {
  // 清除sessionStorage中的数据
  sessionStorage.removeItem('scheduleResult');
  
  // 返回到排产执行页面
  router.push('/scheduling');
};

// 组件挂载时加载数据
onMounted(() => {
  loadScheduleResult();
  
  // 延迟初始化甘特图
  setTimeout(() => {
    if (ganttChartRef.value) {
      ganttChartRef.value.init();
    }
  }, 500);
});
</script>

<style scoped>
.schedule-result-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 5px 0;
  color: #409eff;
  font-size: 24px;
}

.subtitle {
  color: #606266;
  margin: 0;
  font-size: 14px;
}

.header-actions {
  text-align: right;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
}

.page-content {
  max-width: 1400px;
  margin: 0 auto;
}

.stats-card h3,
.gantt-card h3,
.table-card h3 {
  margin: 0;
  color: #409eff;
  font-weight: 600;
}

.stat-item {
  text-align: center;
  padding: 10px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  color: #606266;
  font-size: 14px;
}

.time-info {
  color: #606266;
  font-size: 14px;
  margin-bottom: 10px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60vh;
}

.gantt-card {
  min-height: 600px;
}

.table-card {
  margin-bottom: 20px;
}
</style> 